﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using log4net;

namespace LanguageDetector.Data
{
    public static class CharacterEncodingDB
    {
        static ILog logger = LogManager.GetLogger(typeof(LanguageStatDB));

        public static QueryResult<CharacterEncoding> GetAll()
        {
            var res = new QueryResult<CharacterEncoding>();
            try
            {
                var q = new Query() { Text = "select id,name from character_encoding;" };
                res.Errors.AddRange(q.ExecuteReader(dr =>
                {
                    var c = new CharacterEncoding();
                    c.ID = dr.GetInt32(0);
                    c.Encoding = dr.GetString(1);
                    res.Add(c);
                }));
                if (res.Count > 0)
                {
                    q.Text = "select language,encoding from language_encoding;";
                    var pairs = new List<KeyValuePair<int, int>>();
                    res.Errors.AddRange(q.ExecuteReader(dr =>
                        pairs.Add(new KeyValuePair<int, int>(dr.GetInt32(0), dr.GetInt32(1)))
                    ));
                    if (pairs.Count > 0)
                    {
                        var encMap = (from p in pairs
                                      let t = new { Lang = p.Key, Enc = p.Value }
                                      group t by t.Enc into eGroup
                                      select eGroup).ToDictionary(
                                        g => g.Key,
                                        g => (from i in g select i.Lang).ToArray());
                        for (var i = 0; i < res.Count; i++)
                        {
                            var r = res[i];
                            if (encMap.ContainsKey(r.ID))
                                r.LanguageIDs.AddRange(encMap[r.ID]);
                        }
                    }
                }
            }
            catch (Exception ex) 
            {
                res.Errors.Add(ex);
                logger.Error("Error fetching all language encoding.", ex);
            }
            return res;
        }
    }
}
